package edu.moravian.path;

import edu.moravian.entity.PathEntity;
import edu.moravian.grid.Grid;
import edu.moravian.grid.GridCell;
import edu.moravian.math.Point2D;
import edu.moravian.math.Vector2D;
import edu.moravian.world.WorldDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author ronaghan
 */
public class PathGenerator
{
    private static final String basePath = "src/main/resources/paths";
    
    private Path path;
    private WorldDescriptor world;
    private Grid grid;
    
    public PathGenerator(WorldDescriptor world, Grid grid)
    {
        this.world = world;
        this.grid = grid;
        loadPathFromFile("path1_1.ini");
       
    }
    
    private void loadPathFromFile(String relativePath)
    {
        List<Point2D> points = new ArrayList<Point2D>();
        
        File file = new File(basePath, relativePath);
        try
        {
            Scanner scanner = new Scanner(file);
            
            while(scanner.hasNextLine())
            {
                String line = scanner.nextLine();
                
                String split[] = line.split(" ");
                
                double x = Double.parseDouble(split[0]);
                double y = Double.parseDouble(split[1]);
                
                double worldX = world.getWidth() * x;
                double worldY = world.getHeight() * y;
                
                GridCell cell = grid.getCell(worldX, worldY);
                             
                Point2D point = new Point2D(cell.getCenter());
                points.add(point);
                
            }
            path = new Path(points);
            
            List<Point2D> tempPath = path.getPath();

            
            Point2D startPoint = tempPath.get(0);
            Point2D endPoint;
            for(int i=1; i<tempPath.size() - 1; i++)
            {
                endPoint = new Point2D(tempPath.get(i));
                
                for(int j=0; j<50; j++)
                {
                    Vector2D vecFromAToB = endPoint.minus(startPoint);
                    vecFromAToB.timesEquals((1.0/50.0));
                    
                    Point2D tempPoint = new Point2D(startPoint);
                    tempPoint.scalePlusEquals(j, vecFromAToB);
                    
                    
                  
                    GridCell cell = grid.getCell(tempPoint.getX(), tempPoint.getY());
                    

                    cell.setEntity(new PathEntity());
                }
                
                
                startPoint = endPoint;
            }
                
        }
        catch (FileNotFoundException ex)
        {
            throw new IllegalStateException("can't create scanner for path");
        }
    }
    
    public Path getPath()
    {
        return path;
    }
}
